package com.cskaoyan.service;

import com.cskaoyan.bean.Ad;
import com.cskaoyan.bean.AdExample;
import com.cskaoyan.bean.AdUpdate;
import com.cskaoyan.bean.ListData;
import com.cskaoyan.mapper.AdMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AdServiceImpl implements AdService {
    @Autowired
    AdMapper adMapper;
    @Override
    public ListData<Ad> queryList(Integer page, Integer limit, String name, String content, String sort, String order) {
        PageHelper.startPage(page,limit);
        AdExample adExample = new AdExample();
        adExample.setOrderByClause(sort+ " " + order);
        AdExample.Criteria criteria = adExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (name!=null){
            criteria.andNameLike("%"+name+"%");
        }
        if (content!=null){
            criteria.andNameLike("%"+content+"%");
        }
        List<Ad> ads = adMapper.selectByExample(adExample);
        ListData<Ad> listData = new ListData<>();
        PageInfo<Ad> pageInfo = new PageInfo<>(ads);
        listData.setItems(ads);
        listData.setTotal(pageInfo.getTotal());
        return listData;
    }

    @Override
    public void updateAd(AdUpdate adUpdate) {
        adUpdate.setUpdateTime(new Date());
        int update = adMapper.updateByAdUpdateSelective(adUpdate);
    }

    @Override
    public AdUpdate queryAdUpdate(Integer id) {
        AdUpdate adUpdate = adMapper.selectUpdateById(id);
        return adUpdate;
    }

    @Override
    public void deleteById(Integer id) {
        AdUpdate adUpdate = new AdUpdate();
        adUpdate.setId(id);
        adUpdate.setDeleted(true);
        int delete = adMapper.updateByAdUpdateSelective(adUpdate);
    }

    @Override
    public Ad insertAd(Ad ad) {
        ad.setAddTime(new Date());
        ad.setUpdateTime(new Date());
        int i = adMapper.insertSelective(ad);
        Ad ad1 = adMapper.selectByPrimaryKey(ad.getId());
        return ad1;
    }

}
